package netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * describe:udp 服务器
 *
 * @author helloworldyu
 * @date 2018/5/3
 */
public class NettyUdpServer extends BaseNetworkServer {
	private static final Logger logger = LoggerFactory.getLogger(NettyUdpServer.class);

	/**
	 * udp 服务器使用  DatagramChannel
	 */
	private ChannelInitializer<DatagramChannel> channelInitializer;


	@Override
	public void start() {
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(super.bossGroup)
				.channel(NioDatagramChannel.class)
				.option(ChannelOption.SO_BROADCAST, true)
				.handler(channelInitializer);
		try {
			//服务器绑定端口监听
			bootstrap.bind(port).sync();
			logger.info("启动服务器成功,port={}",port);
		}catch (InterruptedException e){
			//错误日志
			logger.error("启动服务器报错:",e);
		}

	}

	@Override
	public void stop() {
		//异步关闭 EventLoop
		Future<?> future = bossGroup.shutdownGracefully();
		//等待关闭成功
		future.syncUninterruptibly();
		logger.info("退出服务器成功");
	}

	public ChannelInitializer<DatagramChannel> getChannelInitializer() {
		return channelInitializer;
	}

	public void setChannelInitializer(ChannelInitializer<DatagramChannel> channelInitializer) {
		this.channelInitializer = channelInitializer;
	}
}